import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, DatePicker, message} from 'antd';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import WrappedSelect from '../common/WrappedSelect';
import TagSelect from 'Shared/components/TagSelect';
import TextInput from 'Shared/components/TextInput';
import {hasPermissions, formatPrintUrl} from './utils';
import {injectIntl, language, formatMessage} from './intl';
import {newOrder} from './api';
import Export from '../common/Export';
import {secondClaimSummaryStatus} from '../Enum';
import routes from './routes';
import moment from 'moment';
const FormItem = Form.Item;
const {MonthPicker} = DatePicker;
const secondClaimSummaryStatusList = secondClaimSummaryStatus.toList(language);
class QueryPanel extends React.PureComponent {
    state = {
        loading: false
    }
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    onChangeMonthPicker = (value, name) => {
        this.props.onConditionsChange('yearMonth', name);
    }
    onClickCreateBtn = () => {
        this.setState({
            loading: true
        });
        newOrder()
            .then(res => {
                if(res.ok)
                    this.props.querySearch();
                this.setState({
                    loading: false
                });
            });
    }
    onClickPrint = e => {
        e.stopPropagation();
        const {pageIndex, pageSize, isDesc, sortField, supplierCode, secondClaimSummaryDetailCode, ...props} = this.props.conditions;
        if(!props.brandId || !props.yearMonth)
            return message.warn(formatMessage({
                id: 'queryPanel.query.message',
                defaultMessage: '查询条件品牌、年月不能为空'
            }));
        window.open(formatPrintUrl(props));
    }
    render() {
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.print))
            operations.push(<Button key="print" onClick={this.onClickPrint}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.print',
                defaultMessage: '供应商汇总表打印'
            })}</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.supplierSumExcel))
            operations.push(<Export key={PERMISSION.supplierSumExcel} exportButton={this.props.intl.formatMessage({
                id: 'queryPanel.btn.exportSupplierSumExcelButton',
                defaultMessage: '供应商汇总导出'
            })} exportRequest={this.props.onSupplierSumExcelExport} />);
        if(hasPermissions(this.props.permissions, PERMISSION.deliveryListExcel))
            operations.push(<Export key={PERMISSION.deliveryListExcel} exportButton={this.props.intl.formatMessage({
                id: 'queryPanel.btn.exportDeliveryListExcelButton',
                defaultMessage: '送单清单导出'
            })} exportRequest={this.props.onDeliveryListExcelExport} />);
        if(hasPermissions(this.props.permissions, PERMISSION.costSumExcel))
            operations.push(<Export key={PERMISSION.costSumExcel} exportButton={this.props.intl.formatMessage({
                id: 'queryPanel.btn.exportCostSumExcelButton',
                defaultMessage: '费用汇总导出'
            })} exportRequest={this.props.onCostSumExcelExport} />);
        if(hasPermissions(this.props.permissions, PERMISSION.sumTableExcel))
            operations.push(<Export key={PERMISSION.sumTableExcel} exportButton={this.props.intl.formatMessage({
                id: 'queryPanel.btn.exportSumTableExcelButton',
                defaultMessage: '汇总表导出'
            })} exportRequest={this.props.onSumTableExcelExport} />);
        if(hasPermissions(this.props.permissions, PERMISSION.create))
            operations.push(<Button key="create" loading={this.state.loading} type="primary" href={`#${routes.create.url()}`}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.create',
                defaultMessage: '生成'
            })}</Button>);
        let secomdClaimPeriods = this.props.initEnum.secomdClaimPeriods;
        if(this.props.conditions.brandId)
            secomdClaimPeriods = this.props.initEnum.secomdClaimPeriods.filter(v => v.brandId === this.props.conditions.brandId);
        return (
            <Form className="form-standard">
                <Row>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.brandId',
                                defaultMessage: '品牌'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="brandId"
                                value={this.props.conditions.brandId}
                                options={this.props.initEnum.brands}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.yearMonth',
                                defaultMessage: '年月'
                            })}
                            {...FORM_OPTIONS.item}>
                            <MonthPicker
                                placeholder="Select Month"
                                value={this.props.conditions.yearMonth ? moment(this.props.conditions.yearMonth) : undefined}
                                name={this.props.conditions.yearMonth}
                                onChange={this.onChangeMonthPicker} />
                        </FormItem>
                    </Col>
                    {/* <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.secomdClaimPeriodId',
                                defaultMessage: '周期'
                            })}
                            {...FORM_OPTIONS.item}>
                            {this.props.conditions.brandId ? <WrappedSelect
                                allowClear
                                name="secomdClaimPeriodId"
                                value={this.props.conditions.secomdClaimPeriodId}
                                options={secomdClaimPeriods}
                                onChange={this.handleFilterChange} /> : <TextInput name="secomdClaimPeriodId"
                                value={''} disabled placeholder={this.props.intl.formatMessage({
                                    id: 'createPanel.dealerComp.placeholder',
                                    defaultMessage: '请先选择品牌'
                                })} />}
                        </FormItem>
                    </Col> */}
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.secondClaimSummaryDetailCode',
                                defaultMessage: '扣款单号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="secondClaimSummaryDetailCode"
                                value={this.props.conditions.secondClaimSummaryDetailCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.supplierCode',
                                defaultMessage: '供应商编号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="supplierCode"
                                value={this.props.conditions.supplierCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'queryPanel.form.status',
                            defaultMessage: '状态'
                        })} {...FORM_ROW_OPTIONS.item}>
                            <TagSelect
                                name="status"
                                value={this.props.conditions.status}
                                options={secondClaimSummaryStatusList}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.props.onResetClick}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.btn.reset',
                                defaultMessage: '重置'
                            })}
                        </Button>
                    </Col>
                    <Col span={18} className="col-align-right">
                        {operations}
                    </Col>
                </Row>
            </Form>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    initEnum: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onCostSumExcelExport: PropTypes.func.isRequired,
    onDeliveryListExcelExport: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    onSumTableExcelExport: PropTypes.func.isRequired,
    onSupplierSumExcelExport: PropTypes.func.isRequired,
    intl: PropTypes.object
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    resetQueryPanel,
    querySearch,
    deliveryListExcelExportData,
    costSumExcelExportData,
    sumTableExcelExportData,
    supplierSumExcelExportData
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const secomdClaimPeriods = initData.secomdClaimPeriods ? initData.secomdClaimPeriods.map(item => ({
            text: `${'('}${item.code}${')'}${item.startDay} - ${item.endDay}`,
            value: item.id,
            brandId: item.brandId
        })) : [];
        return {
            brands,
            secomdClaimPeriods
        };
    }
);

const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    initEnum: getInitData(state),
    conditions: getConditions(state),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
    onDeliveryListExcelExport: () => dispatch(deliveryListExcelExportData()),
    onCostSumExcelExport: () => dispatch(costSumExcelExportData()),
    onSumTableExcelExport: () => dispatch(sumTableExcelExportData()),
    onSupplierSumExcelExport: () => dispatch(supplierSumExcelExportData()),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
